package com.feiyisys.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.feiyisys.entity.Notice;
import com.feiyisys.mapper.NoticeMapper;
import com.feiyisys.service.NoticeService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

@Service
public class NoticeServiceImpl extends ServiceImpl<NoticeMapper, Notice> implements NoticeService {

    @Override
    public List<Notice> listAllNotices() {
        // 1. 先查"置顶公告"（isTop=1），再查"普通公告"（isTop=0）
        // 2. 均过滤"已删除"数据（isDeleted=0）
        return lambdaQuery()
                .eq(Notice::getIsDeleted, 0)
                .orderByDesc(Notice::getIsTop) // 置顶优先
                .orderByDesc(Notice::getPublishTime) // 发布时间倒序
                .list();
    }

    @Override
    public boolean addNotice(Notice notice) {
        // 手动设置发布时间
        if (notice.getPublishTime() == null) {
            notice.setPublishTime(new Date());
        }

        // 确保逻辑删除字段为0
        if (notice.getIsDeleted() == null) {
            notice.setIsDeleted(0);
        }

        return save(notice);
    }


    @Override
    public boolean updateNotice(Notice notice) {
        // 修改公告，自动填充 updateTime
        return updateById(notice);
    }

    @Override
    public boolean deleteNotice(Long id) {
        return removeById(id);
    }



    @Override
    public Notice getNoticeById(Long id) {
        // 查询未删除的公告
        return lambdaQuery()
                .eq(Notice::getId, id)
                .eq(Notice::getIsDeleted, 0)
                .one();
    }

    @Override
    public List<Notice> listTopNotices() {
        // 仅查询"置顶且未删除"的公告
        return lambdaQuery()
                .eq(Notice::getIsTop, 1)
                .eq(Notice::getIsDeleted, 0)
                .orderByDesc(Notice::getPublishTime)
                .list();
    }

    // 实现分页查询方法
    @Override
    public List<Notice> listNoticesWithPagination(Integer current, Integer size) {
        return lambdaQuery()
                .eq(Notice::getIsDeleted, 0)
                .orderByDesc(Notice::getIsTop)
                .orderByDesc(Notice::getPublishTime)
                .page(new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(current, size))
                .getRecords();
    }

    // 实现统计公告总数方法
    @Override
    public int countNotices() {
        return lambdaQuery()
                .eq(Notice::getIsDeleted, 0)
                .count().intValue();
    }
}
